<template>
    <div :class="isFullScreen?'fullScreen':'not-fullScreen'" style="position: relative;">
        <m-map style="width:100%;height:100%;" :onLoad="mapInit" center="106.40049,39.9208" :zoom="4"></m-map>
        <el-button class='full-screen-btn' round @click='fullScreen()'>{{isFullScreen ? '退出全屏': '全屏查看'}}</el-button>
        <div class="car-type-box">
            <div><p>在线</p><img src="./images/active-h.png" alt=""></div>
            <div><p>离线</p><img src="./images/flameout-h.png" alt=""></div>
        </div>
        <component :is="infoWindow" :detail="vehicleDetail" ref="openInfoWindow"></component>
    </div>
</template>

<script>
    import './map-gather.scss';
    import config from './config';

    const {
        carCountFiled,
        carStatusFiled,
        carTerminalIdFiled,
        lonFiled,
        latFiled,
    } = config;

    export default {
        data() {
            return {
                maplet: null, //地图api
                isFullScreen: false, //是否全屏
                vehicleDetail: null
            }
        },
        props: {
            mapData: {
                type: Array,
                default: []
            },
            getVehicleDetail: Function,
            infoWindow: Object,
            onDragZoom: Function
        },
        watch: {
            mapData: {
                handler(mapData) {
                    this.changeMapData(mapData);
                },
                deep: true
            },
            maplet() {
                this.changeMapData(this.mapData);
            }
        },
        methods: {
            changeMapData(mapData) {
                //if(mapData.length == 0) return;
                this.maplet && this.carRtConverge(mapData);
            },
            addListerner(isInit=false){
                //去掉延迟
                let timeout = null;
                const mapDragZoom = ()=>{
                    if(timeout)timeout.cancel();
                    timeout = this.$timeout(() => {
                        this.onDragZoom(this.getViewBoundAndLevel())
                    },400);
                };
                isInit && mapDragZoom();
                MEvent.addListener(this.maplet, "zoom", mapDragZoom);
                MEvent.addListener(this.maplet, "pan", mapDragZoom);

            },
            removeListerner(){
                MEvent.clearListeners(this.maplet, "zoom");
                MEvent.clearListeners(this.maplet, 'pan');
            },
            mapInit(maplet) {
                //地图初始化和绑定事件
                this.maplet = maplet;
                this.addListerner(true);
                // 查询时设置地图的中心点和级别
                this.$on("initMap",() => {
                   maplet.setCenter(new MPoint("106.40049,39.9208"));
                   maplet.setZoomLevel(4);
                });
            },
            carRtConverge(mapData) {
                this.clearMaker()
                mapData.forEach(e => {
                    let lon = e[lonFiled],
                        lat = e[latFiled];
                    //todo 改这里
                    if(e.carCount !== undefined){
                        this.createClusterMarker(lon, lat, e[carCountFiled]);
                    } else {
                        this.createCarMarker(lon, lat, e[carStatusFiled], e[carTerminalIdFiled]);
                    }

                });
            },
            //获取地图对角经纬度与level
            getViewBoundAndLevel() {
                let vb = this.maplet.getViewBound(),
                    level = this.maplet.getZoomLevel();
                let lflon = vb.LeftDown.split(',')[0],
                    lflat = vb.LeftDown.split(',')[1],
                    rtlon = vb.RightUp.split(',')[0],
                    rtlat = vb.RightUp.split(',')[1];
                return {
                    lflon,
                    lflat,
                    rtlon,
                    rtlat,
                    level
                };
            },
            clearMaker() {
                //清除所有聚合点
                this.maplet.clearOverlays(false);
            },
            createClusterMarker(lon, lat, count) {
                let pt = new MPoint(lon, lat),
                    icon, mk, url;

                const getIcon = (number, count, width) => {
                    return new MIcon(
                        `<div class="blue-cluster-icon${number}e0" style="text-align: center;color:#ffffff;width:${width}px;height:${width}px;line-height:${width}px;">${count}</div>`,
                        width, width, width/2, width/2
                    )
                }

                if(count) {
                    if(0 < count && count <= 10) icon = getIcon(1, count, 54);
                    else if(10 < count && count <= 100) icon = getIcon(2, count, 57);
                    else if(100 < count && count <= 1000) icon = getIcon(3, count, 66);
                    else if(1000 < count && count < 10000) icon = getIcon(4, count, 78);
                    else if(count > 10000) icon = getIcon(5, count, 88);
                }
                mk = new MMarker(pt, icon);
                mk.autoHide = false;
                this.maplet.addOverlay(mk);

                //点击16级以下地图的标记时放大地图
                MEvent.addListener(mk, "click", () => {
                    let le = 0;
                    if(this.maplet.getZoomLevel() < 14 && count > 1) {
                        le = this.maplet.getZoomLevel() + 1;
                    } else {
                        le = 16;
                    }
                    this.maplet.setCenter(pt);
                    this.maplet.setZoomLevel(le);
                });
            },
            //16生成汽车图标
            createCarMarker(lon, lat, zt, vinCode, detailData) {
                let pt = new MPoint(lon, lat),
                    icon, mk,
                    carUrl = [
                        require('./images/active.png'),
                        require('./images/static.png'),
                        require('./images/flameout.png')
                    ];
                if(zt == 1) icon = new MIcon(carUrl[0], 22, 40, 10, 20);
                else if(zt == 3) icon = new MIcon(carUrl[1], 22, 40, 10, 20);
                else if(zt == 2) icon = new MIcon(carUrl[2], 22, 40, 10, 20);
                else icon = new MIcon(carUrl[2], 22, 40, 10, 20);

                mk = new MMarker(pt, icon);
                mk.autoHide = false;
                this.maplet.addOverlay(mk);
                const cMarker = (data) => {
                    this.vehicleDetail = data;
                    this.$nextTick(() => {
                        let dom = this.$refs['openInfoWindow'].$el;
                        let iw = new MInfoWindow("",dom);
                        !mk.info && mk.setInfoWindow(iw);
                        this.$timeout(() => {
                            mk.openInfoWindow();
                        })
                    })
                }

                MEvent.addListener(mk, "click", () => {

                    this.removeListerner();
                 //   this.maplet.setIwStdSize(260, 280);
                    this.maplet.setIwStdSize(300, 350);
                    this.maplet.setIwZoomInSize(300, 400);

                    if(detailData){
//                        cMarker(detailData)
//                        this.$nextTick(() => {
//                            this.addListerner();
//                        });
                    } else {
                        this.getVehicleDetail(vinCode).then(data => {
                            cMarker(data)
                            this.$nextTick(() => {
                                this.addListerner();
                            });
                        }).catch(err => {
                            this.$message.error(err.message);
                        });
                    }
                });

                if(detailData){
                    this.maplet.setIwStdSize(260, 280);
                    cMarker(detailData);
                    mk.openInfoWindow();
                }
            },
            fullScreen() {
                this.isFullScreen = !this.isFullScreen;
                setTimeout(() => {
                    let wh = this.$el.getBoundingClientRect();
                    this.maplet.resize(wh.width, wh.height);
                })
            },
            location2car(detail){
                this.clearMaker();
                this.removeListerner();
                this.maplet.centerAndZoom(detail.longitude+','+detail.latitude, 16);
                this.createCarMarker(detail.longitude, detail.latitude, detail.vehicleStatus,detail.vinCode, detail);
                this.$nextTick(() => {
                    this.addListerner();
                });
            },
            closeInfoWindow(){
                this.maplet.hideBubble();
            }
        }
    }
</script>

<style lang="scss" scoped rel="stylesheet/scss">
    .full-screen-btn {
        width: 80px;
        height: 30px;
        position: absolute;
        top: 10px;
        right: 10px;
        z-index: 999;
    }
    .car-type-box{
        position: absolute;
        padding: 10px;
        top: 50px;
        right: 10px;
        z-index: 999;
        background-color: rgba(0,0,0,0.5);
        color: #FFF;
        >div{
            display: flex;
            flex-direction: row;
            padding-top: 3px;
        }
    }

    .fullScreen{
        position: fixed !important;
        top:0 !important;
        left: 0 !important;
        width: 100% !important;
        height: 100% !important;
        z-index: 1000 !important;
    }
    .not-fullScreen{
        width:100%;
        height:600px;
        position: relative;
        box-sizing: border-box;
    }
</style>
